package com.db.compare.utils;

import com.alibaba.fastjson.JSONObject;
import com.db.compare.utils.SkipHttpsUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.charset.Charset;
import java.util.*;

import static org.apache.http.HttpVersion.HTTP_1_0;

/**
 * 测试结果
 * */
@Slf4j
public class HttpServiceUtils {

    /**
     * 主要用于上传文件
     * */
    public String sendPost(File file, String fileName, String url)throws Exception {
        CloseableHttpClient httpClient = SkipHttpsUtil.wrapClient(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000).build();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        httpPost.setProtocolVersion(HTTP_1_0);
        httpPost.addHeader("cache-control", "no-cache");
        httpPost.addHeader("accept", ContentType.APPLICATION_XML.getMimeType());
        httpPost.addHeader("accept-Language","zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
        httpPost.addHeader("Connection","keep-alive");
        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("file", new FileBody(file))
                .build();//组装归档文件描述XML文件和归档文件做为请求的内容
        // 组装POST请求
        httpPost.setEntity(reqEntity);

        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            System.out.println(Arrays.toString(response.getAllHeaders()));
            System.out.println(response.getStatusLine());
            //获得响应报文的状态值。
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println("Response status code: "+ statusCode);
            //读取响应报文的内容
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                String content= EntityUtils.toString(resEntity,"utf-8");
                JSONObject jsonObject = JSONObject.parseObject(content);
                boolean IsSuccess=jsonObject.getBoolean("IsSuccess");
                if(IsSuccess){
                    return jsonObject.getString("FlagNumer");
                }
            }
            //如果读取内容一定要记得释放响应报文。该函数就是关闭resEntity.getContent()这个InputStream用的。
            EntityUtils.consume(resEntity);
        } finally {
            response.close();
        }
        return "";
    }


    public String doGet(String url, String token, String charset) {
        HttpGet httpGet = null;
        String result = null;
        try {
            CloseableHttpClient httpClient = SkipHttpsUtil.wrapClient(url);
            httpGet = new HttpGet(url);
            //设置参数
            httpGet.addHeader("token", token);
            HttpResponse response = httpClient.execute(httpGet);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, charset);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

    /**
     * 主要用于发送对象
     * */
    public String doPost(String url, String jsonString, String charset) {
        HttpPost httpPost = null;
        String result = null;
        try {
            CloseableHttpClient httpClient = SkipHttpsUtil.wrapClient(url);
            httpPost = new HttpPost(url);
            //设置参数
            httpPost.addHeader("Accept", "application/json");
            httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
//            StringEntity stringEntity = new StringEntity(jsonString);
//            stringEntity.setContentEncoding("UTF-8");
//            stringEntity.setContentType("application/json");
            httpPost.setEntity(new StringEntity(jsonString, Charset.forName("UTF-8")));
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, charset);
                }
            }
        } catch (Exception ex) {
           log.info(ex.getMessage());
           return "error";
        }
        return result;
    }

    /**
     * 一般的post请求
     * */
    public String doPost(String url, Map<String,String> map, String charset) {
        HttpPost httpPost = null;
        String result = null;
        try {
            CloseableHttpClient httpClient = SkipHttpsUtil.wrapClient(url);
            httpPost = new HttpPost(url);
            //设置参数
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            Iterator iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator.next();
                list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
            }
            if (list.size() > 0) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
                entity.setContentType("application/json");
                httpPost.setHeader("Accept", "application/json");
                httpPost.setHeader("Content-type", "application/json;charset=utf-8");
                httpPost.setEntity(entity);
            }
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, charset);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }
}
